<template>
  <el-table
    border
    max-height="500"
    :data="value"
    style="width:100%; font-size:12px"
    :summary-method="getSummaries"
    show-summary
  >
    <el-table-column
      type="index"
      align="center"
    >
    </el-table-column>
    <el-table-column
      prop="manufacturersName"
      min-width="120"
      align="center"
      label="厂家名称">
      <template slot-scope="scope">
        <el-form-item
          v-if="productType == 3"
          label-width="0"
          :rules="[
            {required: true, message: '厂家名称必须', trigger: 'blur'}
          ]"
          :prop="'productParameterList.' + scope.$index + '.manufacturersName'">
          <ManufacturersNameAutoComplete :row="scope.row"></ManufacturersNameAutoComplete>
        </el-form-item>
        <span v-else>
           {{ scope.row.manufacturersName }}
        </span>
      </template>
    </el-table-column>
    <el-table-column
      prop="productNo"
      align="center"
      min-width="100"
      label="商品编号">
    </el-table-column>
    <el-table-column
      prop="bigClass"
      align="center"
      min-width="100"
      label="商品大类">
      <template slot-scope="scope">
        <el-form-item
          v-if="productType == 3"
          label-width="0"
          :prop="'productParameterList.' + scope.$index + '.bigClassNo'">
          <el-select @focus="() => { focusBig(scope.row) }" @change="changeBigClassNo(scope.row)"
                     v-model="scope.row.bigClassNo" :loading="scope.row.loadingBig || false" placeholder="请选择">
            <el-option
              v-for="item in scope.row.optionsBig || []"
              :key="item.value"
              :label="item.text"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <span v-else>
           {{ scope.row.bigClass }}
        </span>
      </template>
    </el-table-column>
    <el-table-column
      prop="middleClass"
      align="center"
      min-width="100"
      label="商品小类">
      <template slot-scope="scope">
        <el-form-item
          v-if="productType == 3"
          :key="scope.$index"
          label-width="0"
          :prop="'productParameterList.' + scope.$index + '.middleClassNo'">
          <el-select @focus="() => { focusMiddle(scope.row) }" v-model="scope.row.middleClassNo"
                     :loading="scope.row.loadingMiddle || false" placeholder="请选择">
            <el-option
              v-for="item in scope.row.optionsMiddle || []"
              :key="item.value"
              :label="item.text"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <span v-else>
           {{ scope.row.middleClass }}
        </span>
      </template>
    </el-table-column>
    <el-table-column
      prop="productName"
      align="center"
      min-width="260"
      label="商品名称">
      <template slot-scope="scope">
        <el-form-item v-if="productType == 3" label-width="0"
                      :prop="'productParameterList.' + scope.$index + '.productName'" :rules="[
          {required: true, message: '商品名称必须', trigger: 'blur'}
        ]">

          <ProductAutoComplete :row="scope.row"></ProductAutoComplete>

        </el-form-item>
        <span v-else>
           {{ scope.row.productName }}
        </span>
      </template>
    </el-table-column>
    <el-table-column
      min-width="80"
      align="center"
      label="房间区域">
      <template slot-scope="scope">
        <el-form-item label-width="0" :prop="'productParameterList.' + scope.$index + '.roomArea'">
          <el-input :maxlength="200" v-model="scope.row.roomArea"/>
        </el-form-item>
      </template>
    </el-table-column>
    <el-table-column
      min-width="80"
      prop="availableNum"
      align="center"
      label="商品可用库存">
      <template slot-scope="scope">
        {{ scope.row.availableNum ? scope.row.availableNum : '/' }}
      </template>
    </el-table-column>
    <el-table-column
      v-if="showArriveNum"
      prop="arriveNum"
      label="到件商品数量">
      <template slot-scope="scope">
        {{ scope.row.arriveNum || scope.row.arriveNum === 0 ? scope.row.arriveNum : '/' }}
      </template>
    </el-table-column>
    <el-table-column
      prop="num"
      min-width="80"
      align="center"
      label="商品数量">
      <template slot-scope="scope">
        <el-form-item label-width="0" :prop="'productParameterList.' + scope.$index + '.num'"
                      :rules="getNumRules(scope.row)">
          <el-input :maxlength="200" v-model="scope.row.num"/>
        </el-form-item>
      </template>
    </el-table-column>
    <el-table-column
      prop="packNum"
      align="center"
      min-width="80"
      label="包件数量">
      <template slot-scope="scope">
        <span v-if="productType == 1">
           {{ (scope.row.packNum = (scope.row.packBuildNum * scope.row.num) || 0) | decimalNumFilter(0) }}
        </span>
        <el-form-item v-else label-width="0" :prop="'productParameterList.' + scope.$index + '.packNum'" :rules="[
          {required: true, message: '包件数必须', trigger: 'blur'},
          {validator: isInteger, message: '包件数必须是整数', trigger: 'blur'},
          {validator: range, min: 1, message: '包件数必须大于1', trigger: 'blur'}
        ]">
          <el-input :maxlength="200" v-model="scope.row.packNum"/>
        </el-form-item>
      </template>
    </el-table-column>
    <el-table-column
      min-width="80"
      prop="installFee"
      align="center"
      label="安装费用">
      <template slot-scope="scope">
        <el-form-item
          label-width="0" :prop="'productParameterList.' + scope.$index + '.installFee'"
          :rules="[
            {validator: isFormatNumber, int: 9,  message: '安装费用必须是小数', trigger: 'blur'},
            {validator: range, min: 0.01,  message: '安装费用必须大于0', trigger: 'blur'}
          ]"
        >
          <el-input :maxlength="200" v-model="scope.row.installFee"/>
        </el-form-item>
      </template>
    </el-table-column>
    <el-table-column
      min-width="80"
      align="center"
      label="备注">
      <template slot-scope="scope">
        <el-form-item label-width="0" :prop="'productParameterList.' + scope.$index + '.memo'">
          <el-input :maxlength="200" v-model="scope.row.memo"/>
        </el-form-item>
      </template>
    </el-table-column>
    <el-table-column
      label="操作"
      align="center"
      min-width="50"
    >
      <template slot-scope="scope">
        <el-button
          :disabled="!!scope.row.arriveNum"
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
</template>
<script>
import ProductAutoComplete from '@/views/oms/order/ProductAutoComplete'
import RelySelect from '@/components/RelySelect'
import ManufacturersNameAutoComplete from '@/views/oms/order/ManufacturersNameAutoComplete'
import {decimalNumFilter} from '@/filters'
import {alert} from '@/utils'
import Emitter from '@/utils/emitter'
import {isInteger, isFormatNumber, range} from '@/utils/validate'
import {mapActions} from 'vuex'

export default {
  name: 'orderPackageTable',
  mixins: [Emitter],
  components: {
    ProductAutoComplete,
    ManufacturersNameAutoComplete,
    RelySelect
  },
  filters: {
    decimalNumFilter
  },
  props: {
    value: {
      type: Array,
      default() {
        return []
      }
    },
    productType: {
      type: Number,
      default: 1
    },
    showShowOverStorage: {
      type: Boolean,
      default: true
    },
    showArriveNum: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    value(val, oldVal) {
      this.$nextTick(_ => {
        this.dispatch('ElFormItem', 'el.form.change', val)
      })
    }
  },
  data() {
    return {
      optionsBig: [],
      optionsMiddle: [],
      loadingBig: false,
      loadingMiddle: false
    }
  },
  methods: {
    isInteger,
    isFormatNumber,
    range,
    getSummaries(param) {
      const {columns, data} = param
      const sums = []
      columns.forEach((column, index) => {
        const values = data.map(item => Number(item[column.property]))
        if (index === 0) {
          sums[index] = '合计'
        } else {
          if (column.property === 'totalVolume' || column.property === 'num' || column.property === 'packNum' || column.property === 'installFee') {
            let temp = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = decimalNumFilter(temp, (column.property === 'num' || column.property === 'packNum') ? 0 : 2)
          } else {
            sums[index] = ''
          }
        }
      })
      return sums
    },
    // 删除
    handleDelete(index, row) {
      this.value.splice(index, 1)
    },
    // 超过可以库存
    overStorage(row) {
      if (this.showShowOverStorage) {
        if (Array.isArray(this.value)) {
          let temp = 0
          this.value.forEach(v => {
            // 计算出输入的总数
            if (v.productId === row.productId) {
              temp += v.num
            }
          })
          if (temp > row.availableNum) {
            return true
          }
        }
      }
      return false
    },
    getNumRules(row) {
      return [
        {required: true, message: '商品数量必须', trigger: 'blur'},
        {validator: this.minArriveNum, min: row.arriveNum, message: '商品数量必须大于到件数量', trigger: 'blur'}
      ]
    },
    minArriveNum(rule, value, callback) {
      if (rule.min) {
        if (value < rule.min) {
          callback(new Error(rule.message || rule.field + '必须是身份证'))
        }
      }
      callback()
    },
    // 获取大类
    focusBig(row) {
      this.$set(row, 'loadingBig', true)
      this.getProductType().then(arr => {
        this.$set(row, 'optionsBig', arr)
      }).finally(_ => {
        this.$set(row, 'loadingBig', false)
      })
    },
    // 获取小类
    focusMiddle(row) {
      if (!row.bigClassNo) {
        alert('请选择商品大类')
        return
      }
      this.$set(row, 'loadingMiddle', true)
      this.getProductType(row.bigClassNo).then(arr => {
        this.$set(row, 'optionsMiddle', arr)
      }).finally(_ => {
        this.$set(row, 'loadingMiddle', false)
      })
    },
    // 商品大类变化了
    changeBigClassNo(row) {
      this.$set(row, 'middleClassNo', '')
    },
    ...mapActions([
      'getProductType'
    ])
  }
}
</script>
